package org.nf.web.mapping;

import jakarta.servlet.http.HttpServletRequest;
import org.nf.web.annotation.RequestMapping;
import org.nf.web.config.Configure;
import org.nf.web.servlet.Controller;
import org.nf.web.servlet.HandlerMapping;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 简单请求处理映射
 *
 * @author zhu
 * @date 2024-05-14
 */
public class SimpleHandlerMapping implements HandlerMapping {

    /**
     * 保存过滤好的 Controller，key为请求的映射地址，value为 Controller 的 Class 对象
     */
    private Map<String, Class<?>> map = new HashMap<String, Class<?>>();

    /**
     * 根据用户请求的 uri 从 map 获取对应的 controllerClass
     * @param request 根据请求地址进行匹配
     * @return
     */
    @Override
    public Object getHandler(HttpServletRequest request) {
        String uri = request.getRequestURI();
        // 去掉 contextPath 的前缀
        uri = uri.replace(request.getContextPath(),"");
        return map.get(uri);
    }

    /**
     * 将带有RequestMapping注解的class过滤并收集起来
     * @param configure configure 配置对象
     */
    @Override
    public void init(Configure configure) {
        // 获取所有扫描的class
        Set<Class<?>> classes = configure.getClasses();
        classes.forEach(clazz -> {
            // 找出带有@RequestMapping注解的class过滤并收集起来
            if (clazz.isAnnotationPresent(RequestMapping.class)
                    && Controller.class.isAssignableFrom(clazz)) {
                String uri = clazz.getAnnotation(RequestMapping.class).value();
                map.put(uri, clazz);
            }
        });
    }
}
